package com.smart.manager.weixin.mp.handler;

import cn.hutool.core.util.StrUtil;
import com.smart.common.entities.constant.SmartConstant;
import com.smart.common.exception.SmartException;
import com.smart.manager.member.repository.MemberProfileMainRepository;
import com.smart.manager.weixin.mp.repository.WeixinMpReplyRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Xiaxuqiu
 *  事件消息处理程式
 * @date 2023-05-13
 **/
@Log4j2
@Component
@RequiredArgsConstructor
public class EventMessageHandler implements WxMpMessageHandler {
    private final WeixinMpReplyRepository weixinMpReplyRepository;
    private final MemberProfileMainRepository memberProfileMainRepository;


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) {
        String appId = wxMpService.getWxMpConfigStorage().getAppId();
        String event = wxMessage.getEvent().toLowerCase();
        switch (event) {
            //关注事件
            case "subscribe":
                return subscribeHandler(wxMpService, wxMessage);
            //取关事件
            case "unsubscribe":
                unsubscribeHandler(appId, wxMessage);
                break;

            case "location":
                return locationHandler(appId, wxMessage);

            case "click":
                return clickReplyHandler(appId, wxMessage);

            //扫描时间处理器
            case "scan":

                decodeQrcode(wxMpService, wxMessage.getFromUser(), wxMessage.getEventKey());
                break;
            default:
                break;
        }

        return null;
    }


    /**
     * 点击回复处理程序
     *
     * @param appId     应用程序id
     * @param wxMessage 天气信息
     * @return {@link WxMpXmlOutMessage}
     */
    private WxMpXmlOutMessage clickReplyHandler(String appId, WxMpXmlMessage wxMessage) {
        String id = wxMessage.getEventKey();
        String fromUser = wxMessage.getFromUser();
        String toUser = wxMessage.getToUser();

        //根据关键字
        return weixinMpReplyRepository.getReplyContentById(appId, toUser, fromUser, id);

    }


    /**
     * 用户关注事件处理程序
     *
     * @param wxMpService wx议员服务
     * @param wxMessage   天气信息
     * @return {@link WxMpXmlOutMessage}
     */
    private WxMpXmlOutMessage subscribeHandler(WxMpService wxMpService, WxMpXmlMessage wxMessage) {
        String appId = wxMpService.getWxMpConfigStorage().getAppId();

        String toUser = wxMessage.getToUser();
        String fromUser = wxMessage.getFromUser();
        String eventKey = wxMessage.getEventKey();
        // 存在二维码参数 开始发送二维码参数
        if (StrUtil.isNotBlank(eventKey)) {decodeQrcode(wxMpService, fromUser, eventKey);}
        return weixinMpReplyRepository.getReplyContentByEvent(appId, toUser, fromUser, "subscribe");


    }


    /**
     * 用户取消关注的处理程序
     * 更新用户关注状态为FALSE
     *
     * @param appId     应用程序id
     * @param wxMessage 天气信息
     */
    private void unsubscribeHandler(String appId, WxMpXmlMessage wxMessage) {
        String openId = wxMessage.getFromUser();
        log.error("监听到取消关注,{} ,{}", appId, openId);
    }


    /**
     * 用户发送经纬事的
     *
     * @param appId     应用程序id
     * @param wxMessage 天气信息
     * @return {@link WxMpXmlOutMessage}
     */
    private WxMpXmlOutMessage locationHandler(String appId, WxMpXmlMessage wxMessage) {
        System.out.println("上报位置信息：" + appId);

        String toUser = wxMessage.getToUser();
        String fromUser = wxMessage.getFromUser();
        Double longitude = wxMessage.getLongitude();
        Double latitude = wxMessage.getLatitude();
        String message = "您上报的地理位置是 经度是：" + longitude + "纬度是:" + latitude;
        // 记录经纬度
        return weixinMpReplyRepository.replyCustomText(toUser, fromUser, message);

    }


    /**
     * 解析代参数的二维码
     *
     * @param wxMpService wx议员服务
     * @param openId      从用户
     */

    public void decodeQrcode(WxMpService wxMpService, String openId, String eventKey) {
        StringBuilder tips = new StringBuilder();
        try {
            // 绑定门店操作员
            if (eventKey.startsWith(SmartConstant.BING_ACCOUNT)) {

                String memberIdStr = eventKey.replace(SmartConstant.BING_ACCOUNT, "");
                Long memberId = Long.valueOf(memberIdStr);
                String result = memberProfileMainRepository.bindMpId(memberId, openId);
                tips.append(result);
            } else {
                tips.append("客服消息监听到带参数的二维码:").append(eventKey);
            }
            WxMpKefuMessage message = WxMpKefuMessage.TEXT().content(tips.toString()).toUser(openId).build();
            wxMpService.getKefuService().sendKefuMessage(message);
        } catch (WxErrorException exception) {
            log.warn("客服消息发送失败:" + exception.getMessage());
            throw new SmartException("客服消息发送失败:" + exception.getMessage());
        }
    }


}